package com.bid.printHtml.web;

import com.bid.printHtml.base.IBasePrintWriter;
import com.fxoa.base.model.FxResponse;
import com.fxoa.base.web.BaseController;
import com.fxoa.exception.ActionException;
import com.rps.clerk.template.model.ClerkTemplate;
import com.rps.clerk.template.service.ClerkTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author liangyonghao
 * @date 2022年08月10日上午 8:52
 */
@RestController
@RequestMapping({"/api/1/printHtml"})
public class PrintHtmlApiController extends BaseController {
    @Resource
    private ApplicationContext applicationContext;
    @Autowired
    private ClerkTemplateService clerkTemplateService;

    @GetMapping("/attachment")
    public FxResponse getAttachment(String referId, String classWriteKey, String templatePath) throws ClassNotFoundException {
        ClerkTemplate clerkTemplate = clerkTemplateService.existsclerkTemplateByclerkTemplateKey(classWriteKey, null);
        if (clerkTemplate == null) {
            throw new ActionException("找不到文书配置");
        }

        String classPath = clerkTemplate.getFullyClassName();
        if (StringUtils.isBlank(classPath)) {
            throw new ActionException("文书配置的全限定类不允许为空");
        }

        Class cls = Class.forName(classPath);
        IBasePrintWriter iw = (IBasePrintWriter) applicationContext.getBean(cls);
        if (iw == null) {
            throw new ActionException("spring找不到对应的类");
        }

        HashMap htmlHasMap = iw.generate(referId, templatePath);
        if (StringUtils.isBlank((String) htmlHasMap.get("content"))) {
            return FxResponse.failure("找不到对应ftl模板");
        }
        return new FxResponse(200, "获取成功", htmlHasMap);
    }
}
